#include "settingsmanager.h"

#include <QDesktopServices>
#include <QStringList>
#include <QDebug>
#include <QFile>
#include <QDir>
#include <QtSql>

#include <urltasks.h>

#define DBNAME    QString("runtimecache.sqlite")
#define DBDRIVE   QString("QSQLITE")
#define TABLENAME QString("urls")

SettingsManager::SettingsManager(QObject *parent)
    : QObject(parent)
    , m_sdb(QSqlDatabase::addDatabase(DBDRIVE))
{
    QString cache_dir(QDesktopServices::storageLocation(QDesktopServices::CacheLocation));
    QDir().mkpath(cache_dir);

    QFile db_file(cache_dir + "/" + DBNAME);
    m_settings_db = db_file.fileName();

    if ( !db_file.open(QFile::ReadWrite) )
        qWarning() << "Cannot access file " << db_file.fileName();
    else
        db_file.close();

    m_sdb.setDatabaseName(m_settings_db);
    if (!db_file.open(QFile::ReadWrite))
        qWarning() << "Cannot open settings database " << db_file.fileName();

    if (m_sdb.open())
    {
        QStringList tables = m_sdb.tables();
        if (!tables.contains(TABLENAME))
        {
            QSqlQuery query = m_sdb.exec("CREATE TABLE " + TABLENAME +
                                       " (url TEXT, file TEXT, status INTEGER);");
            if (!query.isActive())
            {
                qWarning() << "Cannot create table " << TABLENAME;
                qDebug() << query.lastError();
            }
        }
    }
    else
    {
        qWarning() << "Cannot open database " << db_file.fileName();
    }
}

void SettingsManager::load_urls(UrlTasks *tasks)
{
    if (m_sdb.isOpen())
    {
        QSqlQuery query = m_sdb.exec("SELECT url,file,status FROM " + TABLENAME + ";");
        while (query.next())
        {
            tasks->create_new_task(query.value(0).toString()
                                  , query.value(1).toString()
                                  , static_cast<UrlTask::TaskStatus>(query.value(2).toInt()));
        }
    }
}

void SettingsManager::save_urls(QList<UrlTask> const &tasks)
{
    if (m_sdb.isOpen())
    {
        m_sdb.exec("DELETE FROM " + TABLENAME + ";");
        for (QList<UrlTask>::const_iterator i = tasks.begin(); i != tasks.end(); ++i)
        {
            QString query = "INSERT INTO " + TABLENAME + " VALUES ('" + i->get_url()
                    + "', '" + i->get_file() + "', "
                    + QString::number(i->get_status()) + ");";
            m_sdb.exec(query);
        }
    }
}
